package cn.zh.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("4444444444444444444");
        // 1.获取前端请求头中的token信息
        String token = request.getHeader("token");
        // 2.判断前端请求是否携带token，如果携带那么进入判断
        if (!StringUtils.isEmpty(token)) {
            // 2.1.根据token获取到Redis中的用户信息
            Object logininfo = redisTemplate.opsForValue().get(token);
            // 2.2.如果用户信息不为空，那么刷新Redis中token有效期
            if (logininfo != null) {
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
//        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
